package se581.banker.client;

import java.util.Date;

import org.apache.log4j.Logger;

import se581.banker.event.TrackerEvent;
import se581.banker.event.TrackerEventWrapper;
import se581.banker.proxy.TrackerProxy;
import se581.banker.util.Queue;
import se581.banker.util.StaticOutputFileWriterUtil;

/**
 * Client class for queries 
 * 
 * @author mmichalak
 *
 */
public class QueryClient implements Runnable {
	static Logger logger = Logger.getLogger(QueryClient.class.getName());
	
	TrackerProxy proxy = null;
	
	Queue<TrackerEvent> eventQ = new Queue<TrackerEvent>();
	
	
	public void sendQuery() {

		while (!eventQ.isEmpty()) {
			TrackerEvent ev = eventQ.dequeue();
			TrackerEventWrapper evWrapper = new TrackerEventWrapper(ev);
			evWrapper.setStartTime( new Date().getTime() );	// Start time for perf testing
			proxy.processRequest(evWrapper);
			
			logger.debug(evWrapper.getServerReturn());
			
			if (evWrapper.isServerSuccess()) {
				StaticOutputFileWriterUtil.writeToFile(evWrapper.getServerReturn());
			}
			else {
				logger.warn("Query was not successful.  Requeueing event:  " + ev.toString());
				eventQ.enqueue(ev);
			}
			
			logger.info("Elapsed time for Query " + ev.getEventType() + " - " + (new Date().getTime() - evWrapper.getStartTime()) + "     -     " + ev.toEventLine());
		}
		
	}

	public TrackerProxy getProxy() {
		return proxy;
	}

	public void setProxy(TrackerProxy proxy) {
		this.proxy = proxy;
	}
	
	public void addEvent(TrackerEvent ev) {
		eventQ.enqueue(ev);
	}

	
	@Override
	public void run() {
		
		// wake up every second and handle events
		 try {
		        while (true) {
		            Thread.sleep(1 * 1000);	
		            sendQuery();
		        }
		 } catch (InterruptedException e) {
		        e.printStackTrace();
		 }
		
	}

}
